package com.hwtx.form.domain.permission;

import com.google.common.collect.Maps;
import com.hwtx.form.domain.def.meta.config.FormComponentConfig;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;

import java.util.Collection;
import java.util.List;
import java.util.Map;

public class DataQueryInfo {

    public interface DataModelParamParser {
        Map<String, Object> parse(Object value, List<FormComponentConfig.ParamMapping> inputs);
    }

    @Data
    public static class DataModelInfo {
        private String modelName;
        private List<FormComponentConfig.ParamMapping> inputs;
        private List<FormComponentConfig.ParamMapping> outputs;
        private String sqlModelContent;
    }

    @EqualsAndHashCode(callSuper = true)
    @Data
    public static class DataModelParamInfo extends DataModelInfo {
        private String paramName;
        private String table;
        private DataModelParamParser parser;
    }

    @Getter
    @Builder
    public static class DataModelFilterInfo {
        private String table;
        private FormComponentConfig.ParamMapping outputField;
        private String finalSql;
        private List<Object> values;
    }

    @EqualsAndHashCode(callSuper = true)
    @Data
    public static class DataPermInfo extends DataModelInfo {
        List<Map<String, Collection<Object>>> inputValues;
    }

    public static class DefaultDataModelParamParser implements DataModelParamParser {
        public Map<String, Object> parse(Object value, List<FormComponentConfig.ParamMapping> inputs) {
            if (value == null || StringUtils.isBlank(value.toString())) {
                return Map.of();
            }
            Map<String, Object> ret = Maps.newLinkedHashMap();
            String[] values = value.toString().split(",");
            for (int i = 0; i < values.length; i++) {
                FormComponentConfig.ParamMapping paramMapping = inputs.get(i);
                String key = paramMapping.getAlias();
                if (StringUtils.isBlank(key)) {
                    key = paramMapping.getKey();
                }
                ret.put(key, values[i].trim());
            }
            return ret;
        }
    }
}
